<template>
    <div style="color: rgb(255, 255, 255);margin-left: 20vh;margin-top: 2vh;display: inline-block;font-size: 2em;">
        <icon-font type="icon-fanhui" @click="$router.go(-1)"></icon-font>
    </div>
    <div style="margin-top: 2vh;display: inline-block">
        <a-page-header title="设置" sub-title="您可以在此页面编辑您的设置" />
    </div>
    <a-row>
        <a-col :xs="{ span: 22, offset: 1 }" :sm="{ span: 22, offset: 1 }" :md="{ span: 22, offset: 1 }" :lg="{ span: 22, offset: 1 }"
            :xl="{ span: 22, offset: 1 }">
            <a-card
                style="background-color: rgb(247, 249, 252);border-radius: 2vh;width: 120vh;margin-left: 22vh;margin-top: 4vh;">
                <a-row>
                    <a-col :xs="{ span: 6 }" :sm="{ span: 6 }" :md="{ span: 6 }" :lg="{ span: 6 }" :xl="{ span: 6 }">
                        <div style="height: 4vh;">
                            <a-timeline>
                                <a-timeline-item>
                                    <div style="display: inline-block;margin-left: 1vh;">
                                        <a-typography-title :level="3" style="color: rgb(51, 68, 107);">
                                            个人信息</a-typography-title>
                                    </div>
                                </a-timeline-item>
                            </a-timeline>
                        </div>
                        <p style="color: rgb(167, 174, 197);">此信息将显示在您的个人资料中。</p>
                    </a-col>
                    <a-col :xs="{ span: 14, offset: 4 }" :sm="{ span: 14, offset: 4 }" :md="{ span: 14, offset: 4 }"
                        :lg="{ span: 14, offset: 4 }" :xl="{ span: 14, offset: 4 }">
                        <a-form layout="vertical" :hideRequiredMark="true" style="line-height:0.7;">
                            <a-form-item v-bind="validateInfos_profile.username">
                                <div style="display: inline-block; color: rgb(51, 68, 107);">
                                    <strong>用户名称</strong>
                                </div>
                                <template #help>
                                    <p style="margin-left: 8vh;margin-top:1vh; color: rgb(167, 174, 197);">
                                        用户名作为您的登录凭据之一，不会对外公开显示。</p>
                                </template>
                                <div style="display: inline-block;margin-left: 2vh;width: 80%;color: rgb(51, 68, 107);">
                                    <a-input :id="dom_map.profile.username" @blur="
                                        validate_profile('username').catch((_error) => {
                                            logger.warn(_error)
                                        })
                                        " v-model:value="modelRef_profile.username">
                                        <template #addonAfter>
                                            <strong>用户 ID: {{ modelRef_profile.id }}</strong>
                                        </template>
                                    </a-input>
                                </div>
                            </a-form-item>
                            <br />
                            <a-form-item v-bind="validateInfos_profile.email">
                                <div style="display: inline-block;">
                                    <strong style="color: rgb(51, 68, 107);">邮件地址</strong>
                                </div>
                                <template #help>
                                    <p style="margin-left: 8vh;color: rgb(167, 174, 197);">电子邮件地址后续用于登录和重置密码。</p>
                                </template>
                                <!-- <template #help v-else>
                                <p>
                                    请先点击验证邮件中的链接以激活您的电子邮件地址，这封邮件已经发送到
                                    <strong>{{ original_profile.email }}</strong
                                    >。 <br /><a-typography-link
                                        :disabled="disable_resend_link"
                                        :id="dom_map.profile.resend_link"
                                        @click.prevent="send_email"
                                        >重新发送激活邮件</a-typography-link
                                    >
                                </p>
                            </template> -->
                                <div style="display: inline-block;margin-left: 2vh;width: 80%;">
                                    <a-input :id="dom_map.profile.email" :disabled="disable_resend_link" @blur="
                                        validate_profile('email').catch((_error) => {
                                            logger.warn(_error)
                                        })
                                        " v-model:value="modelRef_profile.email" />
                                </div>
                            </a-form-item>
                            <br />
                            <a-form-item v-bind="validateInfos_profile.identity">
                                <div style="display: inline-block;color: rgb(51, 68, 107);">
                                    <strong>职称信息</strong>
                                </div>
                                <template #help>
                                    <p style="margin-left: 8vh;color: rgb(167, 174, 197);">职称信息是个人信息的重要组成部分, 请正确填写</p>
                                </template>
                                <div style="display: inline-block;margin-left: 2vh;width: 80%;color: rgb(51, 68, 107);">
                                    <a-select :id="dom_map.profile.identity" v-model:value="modelRef_profile.identity"
                                        style="color: rgb(51, 68, 107);" @blur="
                                            validate('identity').catch((_error) => {
                                                logger.warn(_error)
                                            })
                                            ">
                                        <a-select-option v-for="item in identityOptions" :key="item.identityId"
                                            :value="item.identityId" :label="item.identityName">
                                            <span>
                                                {{ item.identityName }}
                                            </span>
                                        </a-select-option>
                                    </a-select>
                                </div>
                            </a-form-item>
                            <br />
                            <a-form-item>
                                <template #help>
                                    <p style="margin-left: 8vh;color: rgb(167, 174, 197);">
                                        <br />
                                        以上的所有字段都是可选的，可以在任何时候删除。通过填写它们，您就同意我们在您的用户信息出现的任何地方共享这些数据。请参阅我们的隐私声明，了解更多关于我们如何使用这些信息。
                                    </p>
                                </template>
                                <a-button :id="dom_map.profile.update_profile_button" type="primary"
                                    style="margin-left: 8vh;background-color: rgb(49, 122, 247);border-radius: 20vh;height: 4vh;"
                                    @click.prevent="onSubmit_profile">保存个人信息</a-button>
                            </a-form-item>
                        </a-form></a-col>
                </a-row>
            </a-card>
        </a-col>
    </a-row>
    <a-row>
        <a-col :xs="{ span: 22, offset: 1 }" :sm="{ span: 22, offset: 1 }" :md="{ span: 22, offset: 1 }" :lg="{ span: 22, offset: 1 }"
            :xl="{ span: 22, offset: 1 }">
            <a-card
                style="background-color: rgb(247, 249, 252);border-radius: 2vh;width: 120vh;margin-left: 200px;margin-bottom: 2vh;margin-top: 2vh;">
                <a-row>
                    <a-col :xs="{ span: 6 }" :sm="{ span: 6 }" :md="{ span: 6 }" :lg="{ span: 6 }" :xl="{ span: 6 }">
                        <div style="height: 4vh;">
                            <a-timeline>
                                <a-timeline-item>
                                    <div style="display: inline-block;margin-left: 10px;"><a-typography-title :level="3"
                                            style="color: rgb(51, 68, 107);">密码</a-typography-title>
                                    </div>
                                </a-timeline-item>
                            </a-timeline>
                        </div>
                        <p style="color: rgb(167, 174, 197);">密码更新成功后，您将被重定向到登录页面，您可以使用新密码登录。</p>
                    </a-col>
                    <a-col :xs="{ span: 14, offset: 4 }" :sm="{ span: 14, offset: 4 }" :md="{ span: 14, offset: 4 }"
                        :lg="{ span: 14, offset: 4 }" :xl="{ span: 14, offset: 4 }">
                        <a-form layout="vertical" :hideRequiredMark="true">
                            <a-form-item v-bind="validateInfos_password.old_password">
                                <div style="display: inline-block;color: rgb(51, 68, 107);">
                                    <strong>当前密码</strong>
                                </div>
                                <template #help>
                                    <p style="margin-left: 8vh;color: rgb(167, 174, 197);">要更改密码，您必须确认当前密码填写正确。</p>
                                </template>
                                <div style="display: inline-block;margin-left: 2vh;width: 80%;color: rgb(51, 68, 107);">
                                    <a-input-password :id="dom_map.profile.current_password" autocomplete @blur="
                                        validate_password('old_password').catch((_error) => {
                                            logger.warn(_error)
                                        })
                                        " v-model:value="modelRef_password.old_password" />
                                </div>
                            </a-form-item>
                            <br />
                            <a-form-item v-bind="validateInfos_password.new_password">
                                <div style="display: inline-block;color: rgb(51, 68, 107);margin-left: 1.5vh;">
                                    <strong>新密码</strong>
                                </div>
                                <template #help>
                                    <p style="margin-left: 8vh;color: rgb(167, 174, 197);">新密码长度必须在8-16字符之间。</p>
                                </template>
                                <div style="display: inline-block;margin-left: 2vh;width: 80%;color: rgb(51, 68, 107);">
                                    <a-input-password :id="dom_map.profile.new_password" autocomplete @blur="
                                        validate_password('new_password').catch((_error) => {
                                            logger.warn(_error)
                                        })
                                        " v-model:value="modelRef_password.new_password" />
                                </div>
                            </a-form-item>
                            <br />
                            <a-form-item>
                                <a-button :id="dom_map.profile.update_password_button" type="primary"
                                    style="margin-left: 8vh;background-color: rgb(49, 122, 247);border-radius: 20vh;height: 4vh;"
                                    @click.prevent="onSubmit_password">更新密码</a-button>
                            </a-form-item>
                        </a-form>
                    </a-col>
                </a-row>
            </a-card>
        </a-col>
    </a-row>
</template>

<script>
import { defineComponent, onMounted, reactive, toRaw, toRefs } from 'vue'
import { validate_username } from '@/api/post/validate_username'
import { validate_email } from '@/api/post/validate_email'
import { edit_user_profile } from '@/api/post/edit_user_profile'
import { identity_info } from '@/api/post/identity_info'
import { Form, notification } from 'ant-design-vue'
import { change_password } from '@/api/post/change_password'
import { logout } from '@/api/post/logout'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { user_info } from '@/api/post/user_info'
import { WarningOutlined } from '@ant-design/icons-vue'
import { assign, assignWith } from 'lodash-es'
import dom_map from '@/constant/dom_map'
import logger from '@/util/logger'
import { icon_url } from '@/util/iconfont'
import { createFromIconfontCN } from '@ant-design/icons-vue'

const IconFont = createFromIconfontCN({
    scriptUrl: icon_url

});
export default defineComponent({
    components: {
        WarningOutlined,
        IconFont,
    },
    setup() {
        const store = useStore()
        const $router = useRouter()
        const app_title = process.env.VUE_APP_TITLE
        // prettier-ignore
        const state = reactive({
            modal_visible: false,           // 对话框可见状态
            backGroundImg: require('@/assets/background.png'),
            modal_confirmLoading: false,    // 对话框按钮加载状态
            status: '',                     // 用户状态
            last_login: '',                 // 上次登录时间
            disable_delete_button: true,    // 禁用删除按钮状态
            disable_resend_link: false,     // 禁用发送电子邮件按钮状态
            original_profile: {             // 原始用户信息
                id: 0,
                username: '',
                email: '',
                identity: '',
            },

        })
        // 下拉列表
        const identityOptions = reactive([])
        const showModal = () => {
            state.modal_visible = true
        }
        onMounted(() => {

            initSelect(),
                update()
        })
        const update = () => {
            resetFields_profile()
            resetFields_password()
            user_info().then((response) => {
                if (response.data.status.code === 0) {
                    state.disable_resend_link = false
                    state.status = response.data.data.user.status
                    state.last_login = new Date(parseInt(response.data.data.user.last_login) * 1000).toLocaleString()
                    assign(state.original_profile, response.data.data.user)
                    assign(modelRef_profile, state.original_profile)

                }
            })

        }
        // 下拉列表数据获取
        const initSelect = () => {
            identity_info().then((response) => {
                if (response.data.status.code === 0) {
                    let tmp = response.data.data;
                    for (let i = 0; i < tmp.length; i++) {//循环，选项的个数即为tmp的长度
                        identityOptions.push({
                            identityId: tmp[i].identityId,
                            identityName: tmp[i].identityName,
                        });
                    }
                }
            })

        }
        const modelRef_profile = reactive({
            id: 0,
            username: '',
            email: '',
            identity: '',
        })
        const modelRef_password = reactive({
            old_password: '',
            new_password: '',
        })
        const rulesRef_password = reactive({
            old_password: [
                {
                    required: true,
                    message: '请输入当前密码',
                },
                {
                    trigger: 'blur',
                    min: 8,
                    max: 16,
                    message: '密码长度必须在 8-16 字符之间',
                },
            ],
            new_password: [
                {
                    required: true,
                    message: '请输入新密码',
                },
                {
                    trigger: 'blur',
                    min: 8,
                    max: 16,
                    message: '密码长度必须在 8-16 字符之间',
                },
            ],
        })
        const rulesRef_profile = reactive({
            username: [
                {
                    trigger: 'blur',
                    required: true,
                    message: '请输入用户名',
                    type: 'string',
                },
                {
                    trigger: 'blur',
                    message: '用户名已被占用',
                    validator: (rule, value) => {
                        return new Promise((resolve, reject) => {
                            if (value.length === 0) {
                                resolve()
                            }
                            if (value !== state.original_profile.username) {
                                validate_username(value).then((response) => {
                                    const { code, message } = response.data.status
                                    if (code === 0) {
                                        resolve()
                                    } else {
                                        reject(message)
                                    }
                                })
                            } else {
                                resolve()
                            }
                        })
                    },
                },
                {
                    trigger: 'blur',
                    max: 16,
                    message: '用户名长度上限为 16 字符',
                },
            ],
            email: [
                {
                    trigger: 'blur',
                    required: true,
                    message: '请输入有效的电子邮件地址',
                    type: 'email',
                },
                {
                    trigger: 'blur',
                    message: '电子邮件地址已被占用',
                    validator: (rule, value) => {
                        return new Promise((resolve, reject) => {
                            if (value.toUpperCase() !== state.original_profile.email.toUpperCase()) {
                                validate_email(value).then((response) => {
                                    const { code, message } = response.data.status
                                    if (code === 0) {
                                        resolve()
                                    } else {
                                        reject(message)
                                    }
                                })
                            } else {
                                resolve()
                            }
                        }).catch()
                    },
                },
            ],
            identity: [
                {
                    trigger: 'blur',
                    required: true,
                    message: '请选择职称信息',
                }
            ],
        })
        const onSubmit_profile = () => {
            validate_profile().then(() => {
                const form = toRaw(modelRef_profile)
                const user = {}
                assignWith(user, form, (objValue, srcValue, key) => {
                    return srcValue && srcValue !== state.original_profile[key] ? srcValue : null
                })
                if (user.length === 0) {
                    return
                }
                edit_user_profile(user)
                    .then((response) => {
                        update()
                        if (response.data.status.code === 0) {
                            // 修改成功
                            notification['success']({
                                message: '成功',
                                description: '您的个人信息现已更新。',
                            })
                            // 更新本地用户信息
                            store.dispatch('UPDATE_USER_INFO')
                        } else {
                            notification['error']({
                                message: '您的修改个人信息请求出现错误',
                                description: `个人信息未被修改，因为${response.data.status.message}。`,
                            })
                        }
                    })
                    .catch()
            })
        }
        const onSubmit_password = () => {
            validate_password().then(() => {
                const form = toRaw(modelRef_password)
                change_password(form.old_password, form.new_password).then((response) => {
                    if (response.data.status.code === 0) {
                        // 修改成功
                        notification['success']({
                            message: '成功',
                            description: '您的个人密码现已更新，请使用新密码重新登录。',
                        })
                        logout()
                            .then((response) => {
                                if (response.data) {
                                    // 退出成功
                                    store.commit('SET_LOGOUT', true)
                                    store.commit('CLEAR_USER_INFO')
                                    store.commit('CLEAR_TOKEN')
                                    $router.push('/login')
                                }
                            })
                            .catch()
                    } else {
                        notification['error']({
                            message: '您的修改密码请求出现错误',
                            description: `您的密码未被修改，因为${response.data.status.message}。`,
                        })
                    }
                })
            })
        }
        const {
            resetFields: resetFields_profile,
            validate: validate_profile,
            validateInfos: validateInfos_profile,
        } = Form.useForm(modelRef_profile, rulesRef_profile)
        const {
            resetFields: resetFields_password,
            validate: validate_password,
            validateInfos: validateInfos_password,
        } = Form.useForm(modelRef_password, rulesRef_password)
        return {
            ...toRefs(state),
            resetFields_profile,
            resetFields_password,
            validate_profile,
            identityOptions,
            initSelect,
            validate_password,
            validateInfos_profile,
            validateInfos_password,
            modelRef_profile,
            modelRef_password,
            onSubmit_profile,
            onSubmit_password,
            showModal,
            app_title,
            dom_map,
            logger,
        }
    },
})
</script>

<style scoped>
:deep(.ant-page-header-heading-title) {
    color: rgb(255 255 255);
    font-weight: 520;
    font-size: 2em;
}

:deep(.ant-page-header-heading-sub-title) {
    color: rgb(255, 255, 255);
    font-size: 1em;
}

:deep(.ant-page-header-back-button) {
    color: rgb(255, 255, 255);
}

:deep(.ant-timeline-item-head) {
    width: 3vh;
    height: 3vh;
    background-color: rgb(49, 122, 247);
    border: 1vh solid transparent;
    border-color: #ffffff;
    border-radius: 100%;
    box-shadow: 0 0 0.5vh rgb(179, 177, 177);
}
</style>